# 商品数据
products = [
    {"id": 1, "name": "苹果", "price": 5.0, "stock": 10},
    {"id": 2, "name": "香蕉", "price": 3.0, "stock": 15},
    {"id": 3, "name": "牛奶", "price": 8.0, "stock": 8},
    {"id": 4, "name": "面包", "price": 6.0, "stock": 12}
]

# 购物车
shopping_cart = []

# 用户资金
money = 100.0  # 初始资金
def display_products():
    """显示所有商品"""
    print("\n=== 商品列表 ===")
    print("ID\t商品名\t价格\t库存")
    print("-" * 30)
    for product in products:
        print(f"{product['id']}\t{product['name']}\t{product['price']}元\t{product['stock']}个")


def find_product(product_id):
    """根据ID查找商品"""
    for product in products:
        if product['id'] == product_id:
            return product
    return None


def add_to_cart(product, quantity):
    """添加到购物车"""
    global money

    # 检查库存
    if product['stock'] < quantity:
        print(f"库存不足！该商品只剩 {product['stock']} 个")
        return False

    # 检查余额
    total_price = product['price'] * quantity
    if money < total_price:
        print(f"余额不足！需要 {total_price}元，您只有 {money}元")
        return False

    # 执行购买
    # 更新库存
    product['stock'] -= quantity
    # 扣款
    money -= total_price
    # 添加到购物车
    shopping_cart.append({
        'name': product['name'],
        'price': product['price'],
        'quantity': quantity,
        'total': total_price
    })

    print(f"购买成功！{product['name']} x{quantity}，花费 {total_price}元")
    print(f"您的余额还剩: {money:.2f}元")
    return True


def print_receipt():
    """打印购物小票"""
    if not shopping_cart:
        print("购物车为空！")
        return

    print("\n" + "=" * 40)
    print("           购物小票")
    print("=" * 40)

    total_spent = 0
    for item in shopping_cart:
        print(f"{item['name']:8} x{item['quantity']:2}  {item['price']:6.1f}元  {item['total']:6.1f}元")
        total_spent += item['total']

    print("-" * 40)
    print(f"总计: {total_spent:.1f}元")
    print(f"余额: {money:.1f}元")
    print("=" * 40)
    print("谢谢光临！")


def shopping_process():
    """购物主流程"""
    global money

    print("=== 欢迎来到超市购物系统 ===")
    print(f"您的初始余额: {money}元")

    while True:
        display_products()

        # 用户输入
        choice = input("\n请输入商品ID购买，输入Q/q结账退出: ").strip()

        # 退出条件
        if choice.lower() == 'q':
            print_receipt()
            break

        # 验证输入
        try:
            product_id = int(choice)
        except ValueError:
            print("请输入有效的商品ID！")
            continue

        # 查找商品
        product = find_product(product_id)
        if not product:
            print("没有这个商品，别瞎弄！")
            continue

        # 输入购买数量
        try:
            quantity = int(input(f"请输入购买数量 (当前库存: {product['stock']}): "))
            if quantity <= 0:
                print("数量必须大于0！")
                continue
        except ValueError:
            print("请输入有效数量！")
            continue

        # 执行购买
        add_to_cart(product, quantity)


# 运行程序
if __name__ == "__main__":
    shopping_process()